﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.IO;
using Newtonsoft.Json;

namespace EIIS.Common.Jsons
{
    public static class MVCJsonFormatExtension
    {
        public static MVCJsonFormatResult JsonFormat(this Controller c, object data, string[] exceptMemberName)
        {
            MVCJsonFormatResult result = new MVCJsonFormatResult();
            result.Data = data;
            result.ExceptMemberName = exceptMemberName;
            return result;
        }

        public static MVCJsonFormatResult JsonFormat(this Controller c, object data)
        {
            return JsonFormat(c, data, null);
        }
    }

    public class MVCJsonFormatResult : ActionResult
    {
        public string[] ExceptMemberName { get; set; }
        public Object Data { get; set; }
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = "application/json";

            StringWriter sw = new StringWriter();
            Newtonsoft.Json.Converters.IsoDateTimeConverter timeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
            //这里使用自定义日期格式，如果不使用的话，默认是ISO8601格式
            timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";

            JsonSerializer serializer = JsonSerializer.Create(
                new JsonSerializerSettings
                {
                    Converters = new JsonConverter[] { timeConverter },
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    NullValueHandling = NullValueHandling.Ignore,
                    ContractResolver = new NHibernateContractResolver(ExceptMemberName)
                }
                );

            using (JsonWriter jsonWriter = new JsonTextWriter(sw))
            {
                jsonWriter.Formatting = Formatting.None;
                serializer.Serialize(jsonWriter, Data);
            }
            response.Write(sw.ToString());
        }
    }
}
